# -*- coding: utf-8 -*-
"""
Created on Thu Sep 15 09:27:41 2022

@author: ZXD
"""

import cv2

allNumFea = []

def getBlockFeature(binImg,y_start,x_start,detaH,detaW):
    blackNums = 0
    for i in range(detaH):
        for j in range(detaW):
            if binImg[y_start + i][x_start + j] ==0 :
                blackNums = blackNums+1
    return blackNums

def getNetFeature(binImg):
    height = binImg.shape[0]
    width = binImg.shape[1]
    detaH = int(height/5)
    detaW = int(width/5)
    
    netFea = []
    for i in range(5):
        for j in range(5):
            fea = getBlockFeature(binImg,detaH*i, detaW*j,detaH,detaW)
            netFea.append(fea)
    return netFea

def getImgFeature(img):
    grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    binImg = grayImg.copy()
    height = grayImg.shape[0]
    width = grayImg.shape[1]

    for i in range(height):
        for j in range(width):
            if grayImg[i][j] >100:
                binImg[i][j] = 255
            else:
                binImg[i][j] = 0
    
    #print(getNetFeature(binImg))
    return getNetFeature(binImg)
#img = cv2.imread('../1_1.jpg')
#getImgFeature(img)

def distanceCount(fea1,fea2):
    sum=0
    for i in range(len(fea1)):
        sum = sum + (fea1[i]-fea2[i])*(fea1[i]-fea2[i])
    return sum
    
def numClassifiy(testFea):
    flag = -1
    minDis = 999999
    for i in range(10):
        dis=distanceCount(testFea,allNumFea[i])
        if dis < minDis:
            minDis = dis
            flag = i
            
    return flag

for i in range(10):
    img = cv2.imread('traindata/'+str(i)+'_1.jpg')
    #print('traindata/'+str(i)+'_1.jpg')
    allNumFea.append(getImgFeature(img))
    
    
testImg = cv2.imread('testdata/tgb.jpg')
testFea = getImgFeature(testImg)

print(numClassifiy(testFea))

#print(allNumFea)
#print(len(allNumFea))
    
    

